<?php


namespace App\Services;


use Illuminate\Support\Facades\Redis;

class SmsService
{

    const MOBILE_LIMIT = 30;
    const IP_LIMIT = 30;
    const SMS_SEND_TYPE_OFFLINE = 'offline';

    const API_SEND_URL='https://smssh1.253.com/msg/send/json'; //创蓝发送短信接口URL

    const API_VARIABLE_URL ='https://smssh1.253.com/msg/variable/json';//创蓝变量短信接口URL

    const API_BALANCE_QUERY_URL='https://smssh1.253.com/msg/balance/json';//创蓝短信余额查询接口URL

    const API_ACCOUNT= 'N2628281'; // 创蓝API账号

    const API_PASSWORD= '3BK5KT06VPce87';// 创蓝API密码

    ////创蓝老接口的状态码
//    protected static $fail_short_msg = array(
//        '-1' => '账号未注册', '-2' => '其他错误', '-3' => '帐号或密码错误', '-5' => '余额不足，请充值', '-6' => '定时发送时间不是有效的时间格式',
//        '-7' => '提交信息末尾未签名，请添加中文的企业签名【 】', '-8' => '发送内容需在1到300字之间', '-9' => '发送号码为空',
//        '-10' => '定时时间不能小于系统当前时间', '-100' => 'IP黑名单', '-102' => '账号黑名单', '-103' => 'IP未导入白名单'
//    );
//创蓝接口的状态码
    protected static $fail_short_msg = array(
        '101' => '无此用户', '102' => '密码错误', '103' => '提交过快（提交速度超过流速限制）', '104' => ' 系统忙（因平台侧原因，暂时无法处理提交的短信）', '105' => ' 敏感短信（短信内容包含敏感词）',
        '106' => '消息长度错（>536 或<=0）', '107' => ' 包含错误的手机号码', '108' => ' 手机号码个数错（群发>1000 或<=0）',
        '109' => '无发送额度（该用户可用短信数已使用完）', '110' => '不在发送时间内', '113' => '号码数已达上限', '114' => '可用参数组个数错误（小于最小设定值或者大于 1000）;变量参
数组大于 20 个', '116' => '签名不合法或未带签名（在更换自己的签名需要在平台上报备后方可使用该签名）',
    );
    public static function sendCode($mobile,$type='smsCode'){
        $LimitCheck = self::limitSend($mobile);
        if(!$LimitCheck){
            return ['status'=>false,'msg'=>'您今日获取短信验证码的次数过多'];
        }
        $code = rand(1000,9999);
        $message = '您的验证码为：'.$code.'，请于1分钟内正确输入，如非本人操作，请忽略此短信。';
        //创蓝接口参数
        $postArr = array (
            'account'  =>  self::API_ACCOUNT,
            'password' => self::API_PASSWORD,
            'msg' => urlencode($message),
            'phone' => $mobile,
            'report' => 'true'
        );
        $send_res = self::curlPost( self::API_SEND_URL, $postArr);
        $send_res=json_decode($send_res,true);
        if($send_res['code']==0){
            Redis::setEx($mobile.$type, 300, $code);
            return ['status'=>true,'msg'=>'发送成功'];
        }else{
            return ['status'=>false,'msg'=>self::$fail_short_msg[$send_res['code']]];
        }
    }
//创蓝接口的状态码
    public static function send_msg($mobile,$content)
    {
        header("Content-type: text/html; charset=utf-8");
        //创蓝接口参数
        $postArr = array (
            'account'  =>  self::API_ACCOUNT,
            'password' => self::API_PASSWORD,
            'msg' => urlencode($content),
            'phone' => $mobile,
            'report' => 'true'
        );
        $send_res = self::curlPost( self::API_SEND_URL, $postArr);
        $send_res=json_decode($send_res,true);
        if($send_res['code']==0){
            return ['status'=>true,'msg'=>'发送成功'];
        } else {
            return ['status'=>false,'msg'=>self::$fail_short_msg[$send_res['code']]];
        }

    }

    //发送语音消息
    public static function voiceMarketing($mobile,$content,$templateId=4688){
        header("Content-type: text/html; charset=utf-8");
        //创蓝接口参数还款提醒4609  逾期提醒4611 都来租物扣款失败4617
        //创蓝接口参数还款提醒4688  逾期提醒4611 都来租物扣款失败4617
        $postArr = array (
            'appId'  =>  'RFOPO9So',
            'appKey' => 'imprny6n',
            'mobile'=>$mobile.','.$content,
            'templateId' => $templateId,
            'templateType' => '2',
        );
        $send_res = self::curlUrlPost( 'https://api.253.com/open/market/voice-marketing', $postArr);
        $send_res=json_decode($send_res,true);
        if($send_res['code']=='200000'){
            return ['status'=>true,'msg'=>'发送成功'];
        } else {
            return ['status'=>false,'msg'=>self::$fail_short_msg[$send_res['code']]];
        }
    }

    //创建模板
    public static function createTemplate()
    {
        header("Content-type: text/html; charset=utf-8");
        //创蓝接口参数还款4688  逾期提醒4611 都来租物扣款失败4617
        $postArr = array (
            'appId'  =>  'RFOPO9So',
            'appKey' => 'imprny6n',
            'templateName'=>'都来租物还款提醒',
            'templateContent' => '都来租物提醒您，您的订单将于{1}扣还租金{2}元，请于还款日当天12：00前存入足额资金，以免影响信用记录。如已存足款项或完成还款，请忽略此信息。详询19357616167。感谢您的理解和支持！	',
            'templateType' => '2',
        );
        $send_res = self::curlUrlPost( 'https://api.253.com/data/dgtemplate/createTemplate', $postArr);
        dd($send_res);

        if($send_res['code']==0){
            return ['status'=>true,'msg'=>'发送成功'];
        } else {
            return ['status'=>false,'msg'=>self::$fail_short_msg[$send_res['code']]];
        }

    }

    public static function curlUrlPost($url,$params){
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/x-www-form-urlencoded'   //json版本需要填写  Content-Type: application/json;
            )
        );
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    public static function getTemplateList()
    {
        header("Content-type: text/html; charset=utf-8");
        //创蓝接口参数
        $postArr = array (
            'appId'  =>  'RFOPO9So',
            'appKey' => 'imprny6n',
            'page'=>'1',
        );
        $send_res = self::curlUrlPost( 'https://api.253.com/data/dgtemplate/getTemplateList', $postArr);
        dd($send_res);
        if($send_res['code']==0){
            return ['status'=>true,'msg'=>'发送成功'];
        } else {
            return ['status'=>false,'msg'=>self::$fail_short_msg[$send_res['code']]];
        }

    }

    /**
     * 验证码校验
     * @param $mobile
     * @param $code
     * @param string $type
     * @return bool
     */
    public static function checkCode($mobile,$code,$type='smsCode'){
        $smsCode = Redis::get($mobile.$type);
        if($code != $smsCode){
            return false;
        }
        return true;
    }

    public static function limitSend($mobile){
        $telNum = self::checkLimit('tel_',self::MOBILE_LIMIT,$mobile);
        $codeIpNum = self::checkLimit('codeIp_',self::IP_LIMIT,$_SERVER["REMOTE_ADDR"]);
        if ($telNum < self::MOBILE_LIMIT || $codeIpNum < self::IP_LIMIT) {
            return true;
        } else {
            return false;
        }
    }

    private static function checkLimit($key,$limit,$value)
    {
        $data = Redis::get(self::getLimitCodeKey($key));
        $c_sum = 0;
        if ($data) {
            $row = explode("|", $data);
            $countArr = array_count_values($row);
            if (isset($countArr[$value])) {
                if($countArr[$value] < $limit){
                    self::wirteData($key,$data.$value."|");
                }
                return $countArr[$value];
            }
        }
        self::wirteData($key,$data.$value."|");
        return $c_sum;
    }

    private static function getLimitCodeKey($key){
        return $key . date("Ymd");
    }
    private static function wirteData($key,$data){
        $tomorrow = strtotime(date("Y-m-d 00:00:00",strtotime("+1 day")));
        $sTime = $tomorrow - time();
        Redis::setEx(self::getLimitCodeKey($key), $sTime, $data);
    }


    /**
     * 通过CURL发送HTTP请求
     * @param string $url  //请求URL
     * @param array $postFields //请求参数
     * @return mixed
     *
     */
    private static function curlPost($url,$postFields){
        $postFields = json_encode($postFields);

        $ch = curl_init ();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'   //json版本需要填写  Content-Type: application/json;
            )
        );
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt( $ch, CURLOPT_TIMEOUT,60);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec ( $ch );
        if (false == $ret) {
            $result = curl_error(  $ch);
        } else {
            $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 ". $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
        curl_close ( $ch );
        return $result;
    }


}
